/**
 * 
 */
package t4j.concurrency;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class CloseResource {
	
	public static void main(String[] args) throws Exception {
		ExecutorService exec = Executors.newCachedThreadPool();
		
		ServerSocket server = new ServerSocket(8080);//创建套接字服务器
		
		InputStream socketInput = new Socket("localhost",8080).getInputStream();
		
		exec.execute(new IOBlocked(socketInput));
		
		exec.execute(new IOBlocked(System.in));
		
		TimeUnit.MILLISECONDS.sleep(100);
		
		System.out.println("Shutting down all threads");
		
		exec.shutdownNow();//若把这个注释掉，下面的阻塞的底层资源关闭后，就会抛错，因为IOBlocked有个判断是否中断

		TimeUnit.SECONDS.sleep(1);
		
		System.out.println("Closing " + socketInput.getClass().getName());
		
		socketInput.close();//关闭socket，IOBlocked线程马上就关闭了
		
		TimeUnit.SECONDS.sleep(1);
		
		System.out.println("Closing " + System.in.getClass().getName());
		
		System.in.close();//需要控制台输入后，才关闭线程
		
		
	}
}
